import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import {
  Button,
  Col,
  DatePicker,
  Dropdown,
  Form,
  Input,
  InputNumber,
  Modal,
  message,
  Row,
  Select,
  Spin,
  Table,
  Tabs,
} from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import PopconfirmButton from '@/components/PopconfirmButton';
import {
  projectAdd,
  projectDetail,
  projectEdit,
  userList,
} from '@/services/project';
import { gutter, progressOptions, statusOptions } from '../const/keys';
import AddRecord from './AddRecord';
import UploadFile from './UploadFile';

type ProjectContract = {
  id: number;
  filePath: string;
  fileName: string;
  fileSize: number;
  originalName: string;
  fileType: string;
  createBy?: string;
  createId?: string;
  createTime?: string;
  updateBy?: string;
  updateTime?: string;
  remark?: string;
  params?: {
    [key: string]: any;
  };
};
export type RecordType = {
  id?: number;
  paymentRecordAmount: number; //总金额，单位分
  paymentRecordDesc: string;
  picList: {
    id: number;
    filePath: string;
    fileName: string;
    fileSize: number;
    originalName: string;
    fileType: string;
    createBy?: string;
    createId?: string;
    createTime?: string;
    updateBy?: string;
    updateTime?: string;
    remark?: string;
    params?: {
      [key: string]: any;
    };
  }[];
  projectId: number;
};
type Props = {
  id?: number;
  onClose?: (reflash?: boolean) => void;
};
const App = (props: Props) => {
  const { id, onClose = () => {} } = props;
  const [form] = Form.useForm();
  const [clientSize, setClientSize] = useState<{
    width: number;
    height: number;
  }>({ width: 0, height: 0 });
  const [saveing, setSaving] = useState(false);
  const [spinning, setSpinning] = useState(false);
  const [disabled, setDisabled] = useState(false);
  const [viewImgOpen, setViewImgOpen] = useState(false);
  const [viewImgSrc, setViewImgSrc] = useState('');
  const [recordItem, setRecordItem] = useState<RecordType>();
  const [projectContract, setProjectContract] = useState<ProjectContract[]>([]);
  const [projectPaymentRecordList, setProjectPaymentRecordList] = useState<
    RecordType[]
  >([]);

  const [addOpen, setAddOpen] = useState(false);
  const downloadImg = (url: string) => {
    const link = document.createElement('a');
    link.href = url;
    link.download = 'image.jpg';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };
  const columns = [
    {
      title: '款项阶段描述',
      dataIndex: 'paymentRecordDesc',
      key: 'paymentRecordDesc',
      width: '20%',
    },
    {
      title: '付款金额',
      dataIndex: 'paymentRecordAmount',
      key: 'paymentRecordAmount',
      width: '20%',
      render: (_: any, record: RecordType) =>
        (record.paymentRecordAmount / 100).toFixed(2),
    },
    {
      title: '付款凭证',
      dataIndex: 'picList',
      key: 'picList',
      // ellipsis: true,
      render: (_: any, record: RecordType) => (
        <Row gutter={[10, 10]}>
          {record.picList.map((pic: any) => (
            <Col key={pic.id}>
              <Dropdown
                menu={{
                  items: [
                    {
                      key: 'view',
                      label: '查看图片',
                      onClick: () => {
                        setViewImgOpen(true);
                        setViewImgSrc(pic.dataUrl || pic.filePath);
                      },
                    },
                    //下载图片
                    {
                      key: 'download',
                      label: '下载图片',
                      onClick: () => {
                        downloadImg(pic.dataUrl || pic.filePath);
                      },
                    },
                  ],
                }}
              >
                <img src={pic.dataUrl || pic.filePath} alt="" height={50} />
              </Dropdown>
            </Col>
          ))}
        </Row>
      ),
    },
    //操作
    {
      title: '操作',
      key: 'action',
      width: '20%',
      render: (_text: any, record: any, index: number) => [
        <Button
          key={'edit'}
          type="link"
          icon={<EditOutlined />}
          size="small"
          onClick={() => {
            setRecordItem(record);
            setAddOpen(true);
          }}
        >
          编辑
        </Button>,
        <PopconfirmButton
          title={`确认删除该记录吗？`}
          key={'delete'}
          type="link"
          size="small"
          icon={<DeleteOutlined />}
          onConfirm={() => {
            setProjectPaymentRecordList(
              projectPaymentRecordList.filter((_item, i) => i !== index),
            );
          }}
        >
          删除
        </PopconfirmButton>,
      ],
    },
  ];
  const [userOptions, setUserOptions] = useState<
    Array<{ label: string; value: number }>
  >([]);
  const getData = async () => {
    setSpinning(true);
    const { data } = await userList();

    setUserOptions(
      data.map((item: { id: number; showText: string }) => ({
        label: item.showText,
        value: item.id,
      })),
    );
    if (id !== undefined) {
      const {
        data: projectData = {},
        success,
        msg,
      } = await projectDetail({ id });
      if (!success) {
        message.error(msg || '获取项目详情失败');
      }
      setProjectContract(projectData.projectContract || []);
      setProjectPaymentRecordList(projectData.projectPaymentRecordList || []);
      form.setFieldsValue({
        ...projectData,
        totalAmount:
          projectData.totalAmount === undefined ||
          projectData.totalAmount === null
            ? undefined
            : (projectData.totalAmount || 0) / 100,
        signingTime: projectData.signingTime
          ? dayjs(projectData.signingTime)
          : null,
      });
    }
    setSpinning(false);
  };
  useEffect(() => {
    getData();
  }, []);
  const calculateClientSize = () => {
    const width = window.innerWidth;
    const height = window.innerHeight;
    setClientSize({ width, height });
  };
  useEffect(() => {
    calculateClientSize();
    window.addEventListener('resize', calculateClientSize);
    return () => {
      window.removeEventListener('resize', calculateClientSize);
    };
  }, []);
  const ok = async () => {
    const values = form.getFieldsValue();

    await form.validateFields();
    const totalAmount = values.totalAmount * 100;
    const signingTime = values.signingTime
      ? values.signingTime.format('YYYY-MM-DD')
      : null;

    const submitValues = {
      ...values,
      totalAmount,
      signingTime,
      projectContract,
      projectPaymentRecordList,
    };
    setSaving(true);
    const { success } =
      id !== undefined
        ? await projectEdit({ id, ...submitValues })
        : await projectAdd(submitValues);

    if (success) {
      message.success(`${id ? '编辑' : '新增'}成功`);
      onClose(true);
    }
    setSaving(false);
    // onClose(true);
  };
  const onUploadComplete = (fileList: ProjectContract[]) => {
    setProjectContract(fileList);
  };
  const onEevent = (type: 'start' | 'end') => {
    setDisabled(type === 'start');
  };

  return (
    <>
      <Modal
        width={750}
        open
        //点击背景不能关闭
        maskClosable={false}
        okButtonProps={{
          loading: saveing,
          disabled: disabled || spinning,
        }}
        cancelButtonProps={{
          disabled: disabled,
        }}
        title={`${id ? '编辑' : '新增'}项目工程`}
        onOk={ok}
        onCancel={() => {
          onClose();
        }}
      >
        <Spin spinning={spinning}>
          <Tabs defaultActiveKey="1">
            <Tabs.TabPane tab="基本信息" key="1">
              <Form
                form={form}
                labelCol={{
                  span: 8,
                }}
              >
                <Row gutter={[0, 0]}>
                  <Col span={24}>
                    <Form.Item
                      label="项目名称"
                      name="projectName"
                      rules={[
                        {
                          required: true,
                        },
                      ]}
                      labelCol={{
                        span: 4,
                      }}
                    >
                      <Input placeholder="请输入项目名称" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    {/* 签约时间 */}
                    <Form.Item label="签约时间" name="signingTime">
                      <DatePicker
                        style={{ width: '100%' }}
                        format="YYYY-MM-DD"
                      />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    {/* 总金额 */}
                    <Form.Item label="总金额" name="totalAmount">
                      <InputNumber
                        style={{ width: '100%' }}
                        placeholder="请输入总金额"
                        //两位小数
                        precision={2}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    {/* 项目经理 */}
                    <Form.Item
                      label="项目经理"
                      name="projectManagerUserId"
                      rules={[
                        {
                          required: true,
                        },
                      ]}
                    >
                      <Select
                        options={userOptions}
                        placeholder="请选择项目经理"
                      />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    {/* 业务经理 */}
                    <Form.Item
                      label="业务经理"
                      name="businessManagerUserId"
                      rules={[
                        {
                          required: true,
                        },
                      ]}
                    >
                      <Select
                        options={userOptions}
                        placeholder="请选择业务经理"
                      />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    {/* statusOptions */}
                    <Form.Item
                      label="项目状态"
                      name="projectStatus"
                      rules={[
                        {
                          required: true,
                        },
                      ]}
                    >
                      <Select
                        options={statusOptions}
                        placeholder="请选择项目状态"
                      />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    {/* progressOptions */}
                    <Form.Item
                      label="项目进度"
                      name="projectProgress"
                      rules={[
                        {
                          required: true,
                        },
                      ]}
                    >
                      <Select
                        options={progressOptions}
                        placeholder="请选择项目进度"
                      />
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    {/* progressOptions */}
                    <Form.Item
                      label="备注"
                      name="projectRemark"
                      labelCol={{
                        span: 4,
                      }}
                    >
                      <Input.TextArea placeholder="请输入备注" rows={4} />
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </Tabs.TabPane>
            <Tabs.TabPane tab="项目工程" key="2">
              <UploadFile
                onUploadComplete={onUploadComplete}
                onEevent={onEevent}
                defaultFileList={projectContract?.map((item) => {
                  return { ...item, status: 'done', isOldFile: true };
                })}
              />
            </Tabs.TabPane>
            <Tabs.TabPane tab="付款记录" key="3">
              <Row gutter={[gutter, gutter]}>
                <Col span={24}>
                  <Row justify={'end'}>
                    <Col>
                      <Button
                        type="primary"
                        size="small"
                        ghost
                        icon={<PlusOutlined />}
                        onClick={() => setAddOpen(true)}
                      >
                        新增
                      </Button>
                    </Col>
                  </Row>
                </Col>
                <Col span={24}>
                  <Table
                    columns={columns}
                    size="small"
                    dataSource={projectPaymentRecordList}
                  />
                </Col>
              </Row>
            </Tabs.TabPane>
          </Tabs>
        </Spin>
      </Modal>
      {addOpen ? (
        <AddRecord
          data={recordItem}
          onClose={() => setAddOpen(false)}
          onOk={(item: any) => {
            if (recordItem) {
              //编辑,根据ID替换
              setProjectPaymentRecordList(
                projectPaymentRecordList.map((record) =>
                  record.id === recordItem.id ? item : record,
                ),
              );
            } else {
              //新增
              setProjectPaymentRecordList([...projectPaymentRecordList, item]);
            }
            setAddOpen(false);
          }}
        />
      ) : null}

      {viewImgOpen ? (
        <Modal
          title="查看图片"
          width={clientSize.width * 0.9}
          open
          centered
          footer={null}
          onCancel={() => setViewImgOpen(false)}
        >
          <div
            style={{
              textAlign: 'center',
              height: clientSize.height * 0.8,
              overflowX: 'hidden',
              overflowY: 'auto',
            }}
          >
            <img
              src={viewImgSrc}
              alt=""
              style={{
                maxWidth: '90%',
              }}
            />
          </div>
        </Modal>
      ) : null}
    </>
  );
};
export default App;
